const config = require('./config.js')
const app = getApp();

global.Object = Object
global.Array = Array

global.DataView = DataView
global.Date = Date
global.Error = Error
global.Float32Array = Float32Array
global.Float64Array = Float64Array
global.Function = Function
global.Int8Array = Int8Array
global.Int16Array = Int16Array
global.Int32Array = Int32Array
global.Map = Map
global.Math = Math
global.Promise = Promise
global.RegExp = RegExp
global.Set = Set
global.String = String
global.Symbol = Symbol
global.TypeError = TypeError
global.Uint8Array = Uint8Array
global.Uint8ClampedArray = Uint8ClampedArray
global.Uint16Array = Uint16Array
global.Uint32Array = Uint32Array
global.WeakMap = WeakMap
global.clearTimeout = clearTimeout
global.isFinite = isFinite
global.parseInt = parseInt
global.setTimeout = setTimeout

import _ from './lodash.js'

const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}
const formatDate = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()


  return [year, month, day].map(formatNumber).join('-')
}


const getMonthFirst = () => {
  const year = new Date().getFullYear()
  const month = new Date().getMonth() + 1
  const day = 1;
  return [year, month, day].map(formatNumber).join('-')
}


const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}
const toastError = function (info) {
  wx.showToast({
    title: info,
    icon: 'none',
    duration: 2500,
    mask: false
  })
}
const converErrorCodeToMsg = error => {
  console.log("error", error)
  // error = typeof (error) === "string" ? JSON.parse(error) : error
  // if (error.toString() === 'Error: Network Error') {
  //   console.log('网络错误')
  //   wx.showToast({
  //     title: '网络错误',
  //     icon: 'none'
  //   })
  //   return false
  // }
  if (error.statusCode === 401) {
    // message.error(messageJson['token fail']);

    // setTimeout(function () {
    //   window.location.reload()
    // },1000)
    console.log('401错误')
    wx.showToast({
      title: '登录令牌无效或过期，正在重新登录',
      icon: 'none'
    })
    wx.login({
      success(res) {
        if (res.code) {
          //发起网络请求
          wx.request({
            url: `${config.prefix}/mini_program/login`,
            data: {
              code: res.code,
              type: 2
            },
            method: 'POST',
            success: function(res) {

              console.log('重新新登陆成功', res)
              wx.setStorageSync('userInfo', res.data.data)
              app.globalData.userInfo = res.data.data
              wx.reLaunch({
                url: '/pages/type/type'
              })
            }
          })
        } else {
          console.log('登录失败！' + res.errMsg);

        }
      }
    })
    // wx.showToast({
    //   title: '登录令牌无效或过期，请重新登录',
    //   icon: 'none'
    // })
    // setTimeout(function () {
    //   wx.reLaunch({
    //     url: '/pages/login/login'
    //   })
    // }, 1000)

  } else if (!error.data.errors) {
    console.log('一般错误1')
    wx.showToast({
      title: `${error.data.message}`,
      icon: 'none'
    })
  } else if (error.statusCode === 422) {
    let first;
    for (first in error.data.errors) break;
    console.log('一般错误2')
    wx.showToast({
      title: `${error.data.errors[first][0]}`,
      icon: 'none'
    })
  } else {
    console.log('一般错误4')
    wx.showToast({
      title: '出现错误',
      icon: 'none'
    })
  }
}
const converErrorCodeToMsg_uploadFile = error => {
  console.log("error", error)
  // error = typeof (error) === "string" ? JSON.parse(error) : error
  // if (error.toString() === 'Error: Network Error') {
  //   console.log('网络错误')
  //   wx.showToast({
  //     title: '网络错误',
  //     icon: 'none'
  //   })
  //   return false
  // }
  if (error.statusCode === 401) {
    // message.error(messageJson['token fail']);

    // setTimeout(function () {
    //   window.location.reload()
    // },1000)
    console.log('401错误')
    wx.showToast({
      title: '登录令牌无效或过期，正在重新登录',
      icon: 'none'
    })
    wx.login({
      success(res) {
        if (res.code) {
          //发起网络请求
          wx.request({
            url: `${config.prefix}/mini_program/login`,
            data: {
              code: res.code,
              type: 2
            },
            method: 'POST',
            success: function(res) {

              console.log('重新新登陆成功', res)
              wx.setStorageSync('userInfo', res.data.data)
              app.globalData.userInfo = res.data.data
              wx.reLaunch({
                url: '/pages/index/index'
              })
            }
          })
        } else {
          console.log('登录失败！' + res.errMsg);

        }
      }
    })
    // wx.showToast({
    //   title: '登录令牌无效或过期，请重新登录',
    //   icon: 'none'
    // })
    // setTimeout(function () {
    //   wx.reLaunch({
    //     url: '/pages/login/login'
    //   })
    // }, 1000)

  } else if (!JSON.parse(error.data).errors) {
    console.log('一般错误1')
    wx.showToast({
      title: `${JSON.parse(error.data).message}`,
      icon: 'none'
    })
  } else if (error.statusCode === 422) {
    let first;
    for (first in JSON.parse(error.data).errors) break;
    console.log('一般错误2')
    wx.showToast({
      title: `${JSON.parse(error.data).errors[first][0]}`,
      icon: 'none'
    })
  } else {
    console.log('一般错误4')
    wx.showToast({
      title: '出现错误',
      icon: 'none'
    })
  }
}

const getDistance = function(lat1, lng1, lat2, lng2) {
  lat1 = lat1 || 0;
  lng1 = lng1 || 0;
  lat2 = lat2 || 0;
  lng2 = lng2 || 0;
  var rad1 = lat1 * Math.PI / 180.0;
  var rad2 = lat2 * Math.PI / 180.0;
  var a = rad1 - rad2;
  var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
  var r = 6378137;
  return (r * 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(rad1) * Math.cos(rad2) * Math.pow(Math.sin(b / 2), 2)))).toFixed(0)
}
const getDay = () => {
  const date = new Date();
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  return `${formatNumber(year)}-${formatNumber(month)}-${formatNumber(day)}`
}

const getMonth = () => {
  const date = new Date();
  const year = date.getFullYear();
  const month = date.getMonth() + 1;

  return `${formatNumber(year)}-${formatNumber(month)}`
}
function fixZero(number) {
  if (number < 10) {
    return '0' + number
  }
  else {
    return number
  }
}
function timeStamp(second_time) {

  let time = "0d " + "00:00:" + fixZero(parseInt(second_time));
  if (parseInt(second_time) > 59) {

    let second = fixZero(parseInt(second_time) % 60);
    let min = fixZero(parseInt(second_time / 60));
    time = "0d " + "00:" + min + ":" + second;

    if (min > 59) {
      min = fixZero(parseInt(second_time / 60) % 60);
      let hour = fixZero(parseInt(parseInt(second_time / 60) / 60));
      time = "0d " + hour + ":" + min + ":" + second;

      if (hour > 23) {
        hour = fixZero(parseInt(parseInt(second_time / 60) / 60) % 24);
        let day = parseInt(parseInt(parseInt(second_time / 60) / 60) / 24);
        time = day + "d " + hour + ":" + min + ":" + second;
      }
    }


  }

  return time;
}

function fun_date(num) {
  var date1 = new Date();
  //今天时间
  var time1 = date1.getFullYear() + "-" + (date1.getMonth() + 1) + "-" + date1.getDate()
  console.log(time1);
  var date2 = new Date(date1);
  date2.setDate(date1.getDate() + num);
  //num是正数表示之后的时间，num负数表示之前的时间，0表示今天
  var time2 = formatNumber(date2.getFullYear()) + "-" + formatNumber(date2.getMonth() + 1) + "-" + formatNumber(date2.getDate());
  console.log(time2);
  return time2;
}
function fixedZero(val) {
  return val * 1 < 10 ? `0${val}` : val;
}

function calc(CalcArr){
  let arr = CalcArr.split(" ");
  // console.log(arr);
  let sum = 0;
  arr.forEach((item, index) => {
      sum += parseInt(item, 16);
  });
  let result = sum & 0xff;
  //转换为Hex 16进制（想要10进制可以把toString去掉）
  let result2=result.toString(16).toUpperCase();
  return result2.length<2?'0'+result2:result2;
}
function bleErrCode(errCode){
  if(errCode===0){
    toastError('正常')
    return '正常'
  }else if(errCode===-1){
    toastError('蓝牙已连接')
    return '蓝牙已连接'
  }else if(errCode===10000){
    toastError('未初始化蓝牙适配器,请返回首页重新扫描')
    return '未初始化蓝牙适配器'
  }else if(errCode===10001){
    toastError('当前蓝牙适配器不可用')
    return '当前蓝牙适配器不可用'
  }else if(errCode===10002){
    toastError('没有找到指定设备')
    return '没有找到指定设备'
  }else if(errCode===10003){
    toastError('连接失败')
    return '连接失败'
  }else if(errCode===10004){
    toastError('没有找到指定服务')
    return '没有找到指定服务'
  }else if(errCode===10005){
    toastError('没有找到指定特征')
    return '没有找到指定特征'
  }else if(errCode===10006){
    toastError('当前连接已断开')
    return '当前连接已断开'
  }else if(errCode===10007){
    toastError('当前特征不支持此操作')
    return '当前特征不支持此操作'
  }else if(errCode===10008){
    toastError('其余所有系统上报的异常')
    return '其余所有系统上报的异常'
  }else if(errCode===10009){
    toastError('Android 系统特有，系统版本低于 4.3 不支持 BLE')
    return 'Android 系统特有，系统版本低于 4.3 不支持 BLE'
  }else if(errCode===10012){
    toastError('连接超时')
    return '连接超时'
  }else if(errCode===10013){
    toastError('连接 deviceId 为空或者是格式不正确')
    return '连接 deviceId 为空或者是格式不正确'
  }else{
    toastError('出现未知错误')
    return '出现未知错误'
  }
}

// ArrayBuffer转16进制字符串示例
function ab2hex(buffer) {
  let hexArr = Array.prototype.map.call(
    new Uint8Array(buffer),
    function(bit) {
      return ('00' + bit.toString(16)).slice(-2)
    }
  )
  return hexArr.join('');
}
function padWithZeros(number, length) {
  return String(number).padStart(length, '0');
}
function isValidIPv4(ip) {
  const ipRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
  return ipRegex.test(ip);
}
function hexToAscii(hexStr) {
  let asciiStr = '';
  for (let i = 0; i < hexStr.length; i += 2) {
    const hexCharCode = hexStr.substr(i, 2);
    const charCode = parseInt(hexCharCode, 16);
    asciiStr += String.fromCharCode(charCode);
  }
  return asciiStr;
}
function hexToSignedInt(hex) {
  if (hex.length % 2 != 0) {
      hex = "0" + hex;
  }
  let num = parseInt(hex, 16);
  let maxVal = Math.pow(2, (hex.length / 2) * 8);
  if (num > maxVal / 2 - 1) {
      //这里是判断正负，最高位为1，就代表正数
      num = num - maxVal;
  }
  return num;
}
function hex2int(hexStr) {
  let twoStr = parseInt(hexStr,16).toString(2); // 将十六转十进制，再转2进制
  let bitNum = hexStr.length * 4; // 1个字节 = 8bit ，0xff 一个 "f"就是4位
  if(twoStr.length < bitNum){
    while(twoStr.length < bitNum){
      twoStr = "0" + twoStr;
    }
  }
  if(twoStr.substring(0,1) == "0"){
    // 正数
    twoStr = parseInt(twoStr,2); // 二进制转十进制
    return twoStr;
  }else{
    // 负数
    let twoStr_unsign = "";

    console.log("hex2int--->"+parseInt(twoStr,2));
    twoStr = parseInt(twoStr,2) - 1; // 补码：(负数)反码+1，符号位不变；相对十进制来说也是 +1，但这里是负数，+1就是绝对值数据-1
    // console.log("hex2int--->"+twoStr);

    twoStr = twoStr.toString(2);
    twoStr_unsign = twoStr.substring(1,bitNum); // 舍弃首位(符号位)
    // 去除首字符，将0转为1，将1转为0   反码
    twoStr_unsign = twoStr_unsign.replace(/0/g, "z");
    twoStr_unsign = twoStr_unsign.replace(/1/g, "0");
    twoStr_unsign = twoStr_unsign.replace(/z/g, "1");

    // console.log("hex2int--->"+twoStr_unsign);
    // console.log("hex2int--->"+(-twoStr_unsign));
    twoStr = parseInt(-twoStr_unsign, 2);
    return twoStr;
  }
}
function binaryToHexString(binaryString) {
  let decimal = parseInt(binaryString, 2); // 将二进制字符串转换为十进制数
  let hexadecimal = decimal.toString(16); // 将十进制数转换为十六进制字符串
  return hexadecimal;
}
function addSpaceEveryTwoChars(str) {
  return str.replace(/(.{2})(?=.)/g, '$1 ');
}
function splitStringByLength(str, len) {
  return str.match(new RegExp('.{1,' + len + '}', 'g')) || [];
}
const formatTime2 = () => {
	const date = new Date();
	const year = date.getFullYear()
	const month = date.getMonth() + 1
	const day = date.getDate()
	const weekDay = ['日', '一', '二', '三', '四', '五', '六'][date.getDay()]
	const hour = date.getHours()
	const minute = date.getMinutes()
	const second = date.getSeconds()
	return {
		date: [year, month, day].map(formatNumber).join('-'),
		time:[hour, minute, second].map(formatNumber).join(':'),
		week: '星期'+weekDay
	}
}

function renderMeterStatus(val) {
  const parseST1=parseInt(val.substr(2,2),16).toString(2).padStart(8, '0')
  const b0=parseST1.substr(7,1)
  const b1=parseST1.substr(6,1)
  const b2=parseST1.substr(5,1)
  const b3=parseST1.substr(4,1)
  const b4=parseST1.substr(3,1)
  let alarmTags=[]
  if(b0==='1'){
    alarmTags.push('压力报警')
  }
  if(b1==='1'){
    alarmTags.push('温度报警')
  }
  if(b2==='1'){
    alarmTags.push('持续流量报警')
  }
  if(b3==='1'){
    alarmTags.push('倾斜报警')
  }
  if(b4==='1'){
    alarmTags.push('有流量')
  }
  if(alarmTags.length>0){
    return alarmTags
  }else{
    return  '正常'
  }

}
let timer = null;
const throttle = (fn, wait) => {
  let context = this;
  let args = arguments;

  if (!timer) {
    timer = setTimeout(() => {
      fn.apply(context, args);
      timer = null;
    }, wait)
  }
}
function getLast7Days() {
  let currentDate = new Date();
  let millisecondsInADay = 24 * 60 * 60 * 1000; // 一天有24小时，每小时60分钟，每分钟60秒，每秒1000毫秒
  let millisecondsIn7Days = 7 * millisecondsInADay;
  let date7DaysAgo = new Date(currentDate.getTime() - millisecondsIn7Days);

  let year = date7DaysAgo.getFullYear();
  let month = (date7DaysAgo.getMonth() + 1).toString().padStart(2, '0'); // 月份从0开始，需要加1并填充前导零
  let day = date7DaysAgo.getDate().toString().padStart(2, '0'); // 日期需要填充前导零
  let formattedDate = year + '-' + month + '-' + day;
  return formattedDate
}

module.exports = {
  throttle:throttle,
  getDistance: getDistance,
  renderMeterStatus:renderMeterStatus,
  formatTime: formatTime,
  formatNumber: formatNumber,
  formatTime2:formatTime2,
  converErrorCodeToMsg: converErrorCodeToMsg,
  getDay: getDay,
  getMonth: getMonth,
  timeStamp: timeStamp,
  formatDate: formatDate,
  fun_date: fun_date,
  getMonthFirst: getMonthFirst,
  fixedZero:fixedZero,
  converErrorCodeToMsg_uploadFile:converErrorCodeToMsg_uploadFile,
  toastError: toastError,
  calc:calc,
  bleErrCode:bleErrCode,
  ab2hex:ab2hex,
  padWithZeros:padWithZeros,
  isValidIPv4:isValidIPv4,
  hexToAscii:hexToAscii,
  hexToSignedInt:hexToSignedInt,
  hex2int:hex2int,
  binaryToHexString:binaryToHexString,
  addSpaceEveryTwoChars:addSpaceEveryTwoChars,
  splitStringByLength:splitStringByLength,
  getLast7Days:getLast7Days
}